package com.fg.cloud.framework.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fg.cloud.common.finals.UserType;
import com.fg.cloud.common.shiro.CustomLoginToken;
import com.fg.cloud.common.shiro.ShiroUser;
import com.fg.cloud.common.shiro.UserUtils;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;

/**
 * Description:游客模式Realm
 * @author around
 * @date 2017年9月14日下午5:56:53
 */
public class GuestRealm extends AuthorizingRealm  {

	private static Logger LOGGER = LoggerFactory.getLogger(GuestRealm.class);
	
	@Override
	public String getName() {
		return UserType.GUEST;
	}
	
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		LOGGER.info("Shiro-guest登录认证");
		CustomLoginToken authcToken = (CustomLoginToken) token;
		AgencyUserVo user = new AgencyUserVo();
		user.setFacId(2L);
		
		ShiroUser shiroUser = new ShiroUser(user.getId(), user.getUserName(), 
        		user.getTrueName(), getName());
        setCurrentUser(user);
		return new SimpleAuthenticationInfo(shiroUser, authcToken.getPassword(), getName());
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//校验正确的当前用户
		if (!principals.getRealmNames().contains(getName())) return null;
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRole(UserType.GUEST);
		
		return info;
	}

	private void setCurrentUser(Object user){
        UserUtils.setCurrentUser(user);
    }

}
